'use strict';

const BaseService = require('./base');
const modelName = 'Major';

class MajorService extends BaseService {
  constructor(ctx) {
    super(ctx, modelName);
  }

  getInclude() {
    return [
      {
        model: this.ctx.model.School,
        attributes: ['name'],
      },
      {
        model: this.ctx.model.ApplyDate,
        as: 'applyDate'
      }
    ];
  }
  // 创建
  async create(data) {
    delete data.id
    // 去重验证 同一个学校不能存在相当同的编码或者名称
    const isExist = await this.ctx.model.Major.findOne({
      where: {
        major: data.major,
        school_id: data.school_id
      }
    })
    if (isExist) {
      throw new Error('该学校已存在相同的专业')
    }
    const res = await super.create(data)
    // 再创建applyDate
    if (data.applyDate.length) {
      await this.ctx.model.ApplyDate.bulkCreate(data.applyDate.map(item => {
        return {
          ...item,
          major_id: res.id
        }
      }))
    }

    if (data.course && data.course.length) {
      await this.ctx.model.Course.bulkCreate(data.course.map(item => {
        return {
          ...item,
          major_id: res.id
        }
      }))
    }
    return res
  }
  async update(id,data) {
    await super.update(id,data)
    // 删除日期
    await this.ctx.model.ApplyDate.destroy({
      where: {
        major_id: id
      }
    })
    // 再创建applyDate
    if (data.applyDate.length) {
      await this.ctx.model.ApplyDate.bulkCreate(data.applyDate.map(item => {
        return {
          ...item,
          major_id: id
        }
      }))
    }
    return true
  }

  async createList(data) {
    let list = []
    let errList = []
    for (const majorData of data) {
      try {
        let school = await this.ctx.model.School.findOne({
          where: {
            name: majorData.school_name
          }
        })
        if (!school) {
          school = await this.ctx.model.School.create({
            name: majorData.school_name,
            lang: majorData.lang
          })
        }
        majorData.school_id = school.id
        const res = await this.create(majorData)
        list.push(res)
      } catch (e) {
        console.log('err',e.message)
        errList.push({
          ...majorData,
          errorMessage: e.message
        })
      }
    }
    return {
      successList: list,
      errList
    }
  }

  async deleteById(id) {
    await super.deleteById(id)
    console.log('删除')
    await this.ctx.model.ApplyDate.destroy({
      where: {
        major_id: id
      }
    })
    await this.ctx.model.Course.destroy({
      where: {
        major_id: id
      }
    })
    return true
  }
}

module.exports = MajorService;
